﻿#region USING
using System;
using System.IO;
using System.Drawing;
using System.Windows.Forms;
using NHTLibrary;
using NHTClient.Objects;
using NHTClient.Internals;
using Awesomium.Core;
using DevExpress.Utils;
using DevExpress.XtraTab;
using DevExpress.XtraEditors;
using DevExpress.XtraTab.ViewInfo;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraTabbedMdi;
#endregion

namespace NHTClient
{
    public partial class NHTMain : XtraForm
    {
        #region MEMBERS
        private Point point = Point.Empty;
        private XtraTabPage page = null;
        private Boolean isFullDesktop;

        private const String NHT_PLAY_URI_DEFAULT = "http://5.maxgate.vn/play/s";

        public ServerCore SERVER;
        public Int16 SERVER_NUMBER { get; set; }

        private Boolean FullDesktop
        {
            get
            {
                return isFullDesktop;
            }
            set
            {
                if (isFullDesktop != value)
                {
                    isFullDesktop = value;
                    switch (FullDesktop)
                    {
                        case false:
                            statusBar.Visible = !isFullDesktop;
                            FormBorderStyle = FormBorderStyle.FixedSingle;
                            break;
                        case true:
                            statusBar.Visible = !isFullDesktop;
                            FormBorderStyle = FormBorderStyle.None;
                            break;
                    }
                }
            }
        }
        #endregion

        #region CONSTRUCTORS
        public NHTMain()
        {
            InitializeComponent();
        }
        #endregion

        #region CORE-METHODS
        /// <summary>
        /// Perform new login
        /// </summary>
        /// <param name="_serverCode">The server number must be Integer 16bit</param>
        public void NewLogin(Int16 _serverCode)
        {
            OpenTab(String.Format("{0}{1}", NHT_PLAY_URI_DEFAULT, _serverCode));
        }

        /// <summary>
        /// If WebCore already initialized then shutdown it
        /// Delete all contents entire Profiles folder (//UserData//Profiles//*)
        /// </summary>
        private void ExitApplication()
        {
            if (WebCore.IsInitialized)
            {
                WebCore.Shutdown();
            }

            Directory.Delete(String.Format("{0}{1}UserData{2}Profiles", Path.GetDirectoryName(Application.ExecutablePath), Path.DirectorySeparatorChar, Path.DirectorySeparatorChar), true);
            Close();
        }
        #endregion

        #region WEBCORE-METHODS
        /// <summary>
        /// Create new web session and append it into tab control
        /// </summary>
        /// <param name="insertIndex">Tab index</param>
        /// <param name="url">Url we need forwarded to</param>
        private void OpenTab(String url, Int32? insertIndex = null)
        {
            browserTabControl.SuspendLayout();

            var browser = new WebDocument(url)
            {
                Dock = DockStyle.Fill,
            };

            var tabPage = new XtraTabPage() { ShowCloseButton = DefaultBoolean.True };

            browserTabControl.TabPages.Add(tabPage);
            tabPage.Controls.Add(browser);

            if (insertIndex == null)
            {
                browserTabControl.TabPages.Add(tabPage);
            }
            else
            {
                browserTabControl.TabPages.Insert(insertIndex.Value, tabPage);
            }

            browserTabControl.SelectedTabPage = tabPage;

            browserTabControl.ResumeLayout(true);
        }

        /// <summary>
        /// Get the current tab
        /// </summary>
        /// <returns>The current control in selected tabpage</returns>
        private WebDocument GetCurrentTabControl()
        {
            if (browserTabControl.SelectedTabPageIndex == -1)
            {
                return null;
            }

            var tabPage = browserTabControl.TabPages[browserTabControl.SelectedTabPageIndex];
            var control = (WebDocument)tabPage.Controls[0];

            return control;
        }

        /// <summary>
        /// Perform refresh web control in the current tabpage
        /// </summary>
        private void RefreshBrowser()
        {
            var control = GetCurrentTabControl();
            if (control != null)
            {
                if (!control.Browser.IsLoading)
                {
                    control.Browser.Reload(false);
                }
            }
        }
        #endregion

        #region CUSTOM-HEADER-BAR
        private void OnNewLoginClick()
        {
            using (var form = new NHTServerList(this))
            {
                form.ShowIcon = false;
                form.ShowInTaskbar = false;
                form.ShowDialog();
            }
        }

        private void OnPaymentClick()
        {
            using (var form = new NHTPayment(this))
            {
                form.ShowIcon = false;
                form.ShowInTaskbar = false;
                form.ShowDialog();
            }
        }

        private void OnChatClick()
        {
            using (var form = new NHTChat(this))
            {
                form.ShowIcon = false;
                form.ShowInTaskbar = false;
                form.ShowDialog();
            }
        }

        private void OnRefreshBrowserClick()
        {
            RefreshBrowser();
        }

        private void OnSettingClick()
        {
            XtraMessageBox.Show("Chức năng này sẽ được cập nhật trong phiên bản 2.0!", "Thông Báo", MessageBoxButtons.OK);
        }

        private void OnSwitchFullDesktopClick()
        {
            FullDesktop = !FullDesktop;
        }
        #endregion

        #region EVENT-HANDLER
        private void NHTMain_Load(object sender, EventArgs e)
        {
            Localizer.Active = new VietnameseEditorLocalizer();
            SERVER = new ServerCore();

            bsiLicenseGuid.Caption += Guid.NewGuid().ToString();
            bsiProductVersion.Caption += Application.ProductVersion;
            bsiSystemTime.Caption += DateTime.Now.ToString("T");
            bsiEventCountdown.Caption += DateTime.Now.ToUniversalTime().ToString("T");

            localTimer.Enabled = true;
            localTimer.Interval = 1000;
            localTimer.Start();
            localTimer.Tick += OnLocalTimerTick;

            eventTimer.Enabled = true;
            eventTimer.Interval = 1000;
            eventTimer.Start();
            eventTimer.Tick += OnEventTimerTick;
        }

        private void OnLocalTimerTick(object sender, EventArgs e)
        {
            bsiSystemTime.Caption = String.Format("Thời gian: {0}", DateTime.Now.ToString("T"));
        }

        private void OnEventTimerTick(object sender, EventArgs e)
        {
            bsiEventCountdown.Caption = String.Format("Event kế tiếp: {0}", DateTime.Now.ToUniversalTime().ToString("T"));
        }

        private void NHTMain_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.F1:
                    OnNewLoginClick();
                    break;
                case Keys.F2:
                    OnPaymentClick();
                    break;
                case Keys.F3:
                    OnChatClick();
                    break;
                case Keys.F5:
                    OnRefreshBrowserClick();
                    break;
                case Keys.F10:
                    OnSettingClick();
                    break;
                case Keys.F12:
                    OnSwitchFullDesktopClick();
                    break;
                default:
                    break;
            }
        }

        private void browserTabControl_CustomHeaderButtonClick(object sender, DevExpress.XtraTab.ViewInfo.CustomHeaderButtonEventArgs e)
        {
            XtraTabControl tabControl = sender as XtraTabControl;

            if (e.Button == tabControl.CustomHeaderButtons[0])
            {
                OnNewLoginClick();
            }
            else if (e.Button == tabControl.CustomHeaderButtons[1])
            {
                OnPaymentClick();
            }
            else if (e.Button == tabControl.CustomHeaderButtons[2])
            {
                OnChatClick();
            }
            else if (e.Button == tabControl.CustomHeaderButtons[3])
            {
                OnRefreshBrowserClick();
            }
            else if (e.Button == tabControl.CustomHeaderButtons[4])
            {
                OnSettingClick();
            }
            else if (e.Button == tabControl.CustomHeaderButtons[5])
            {
                OnSwitchFullDesktopClick();
            }
        }

        private void browserTabControl_CloseButtonClick(object sender, EventArgs e)
        {
            XtraTabControl tabControl = sender as XtraTabControl;

            if (tabControl.TabPages.Count == 0)
            {
                return;
            }

            var currentIndex = tabControl.SelectedTabPageIndex;

            var tabPage = tabControl.TabPages[currentIndex];

            var control = GetCurrentTabControl();
            if (control != null)
            {
                control.Dispose();
            }

            tabControl.TabPages.Remove(tabPage);
            tabControl.SelectedTabPageIndex = currentIndex - 1;

            if (tabControl.TabPages.Count == 0)
            {
                ExitApplication();
            }
        }

        private void browserTabControl_TabMiddleClick(object sender, PageEventArgs e)
        {
            XtraTabControl tabControl = sender as XtraTabControl;

            if (tabControl.TabPages.Count == 0)
            {
                return;
            }

            var currentIndex = tabControl.SelectedTabPageIndex;

            var tabPage = tabControl.TabPages[currentIndex];

            var control = GetCurrentTabControl();
            if (control != null)
            {
                control.Dispose();
            }

            tabControl.TabPages.Remove(tabPage);
            tabControl.SelectedTabPageIndex = currentIndex - 1;

            if (tabControl.TabPages.Count == 0)
            {
                ExitApplication();
            }
        }

        private void browserTabControl_MouseDown(object sender, MouseEventArgs e)
        {
            XtraTabControl tabControl = sender as XtraTabControl;
            point = new Point(e.X, e.Y);
            XtraTabHitInfo hi = tabControl.CalcHitInfo(point);
            page = hi.Page;
            if (hi.Page == null)
                point = Point.Empty;
        }

        private void browserTabControl_MouseMove(object sender, MouseEventArgs e)
        {
            XtraTabControl tabControl = sender as XtraTabControl;
            if (e.Button == MouseButtons.Left)
            {
                if ((point != Point.Empty) && ((Math.Abs(e.X - point.X) > SystemInformation.DragSize.Width) || (Math.Abs(e.Y - point.Y) > SystemInformation.DragSize.Height)))
                {
                    tabControl.DoDragDrop(sender, DragDropEffects.Move);
                }
            }
        }

        private void browserTabControl_DragOver(object sender, DragEventArgs e)
        {
            XtraTabControl tabControl = sender as XtraTabControl;
            if (tabControl == null) return;
            XtraTabHitInfo hi = tabControl.CalcHitInfo(tabControl.PointToClient(new Point(e.X, e.Y)));
            if (hi.Page != null)
            {
                if (hi.Page != page)
                {
                    if (tabControl.TabPages.IndexOf(hi.Page) < tabControl.TabPages.IndexOf(page))
                    {
                        tabControl.TabPages.Move(tabControl.TabPages.IndexOf(hi.Page), page);
                    }
                    else
                    {
                        tabControl.TabPages.Move(tabControl.TabPages.IndexOf(hi.Page) + 1, page);
                    }
                }
                e.Effect = DragDropEffects.Move;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }

        /// <summary>
        /// The child has data available - get it.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void serverList_DataAvailable(object sender, EventArgs e)
        {
            NHTServerList child = sender as NHTServerList;
            if (child != null)
            {
                SERVER_NUMBER = child.Data;
            }
        }
        #endregion
    }
}
